package Admin;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.util.List;

import javax.swing.AbstractButton;
import javax.swing.JOptionPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;

import Admin.TownFree.MyItemListener;
import GroupClass.ConnectRMI;
import Project_etow.EtowInterface;

public class UnitFree extends javax.swing.JDialog
{

    private int               row , dem;
    ConnectRMI                connectRMI = new ConnectRMI();
    private static String     chua;
    private String            click1 , click2 , click3;
    private static String     a1 , a2 , a3;
    private String            checkviable;
    private DefaultTableModel dtm;

    
    private int Countvalueunit;
    
    

    public int getCountvalueunit()
    {
        return Countvalueunit;
    }

    public void setCountvalueunit(int countvalueunit)
    {
        Countvalueunit = countvalueunit;
    }

    public String getCheckviable()
    {
        return checkviable;
    }

    public void setCheckviable(String checkviable)
    {
        this.checkviable = checkviable;
    }

    private String floorId;

    public String getFloorId()
    {
        return floorId;
    }

    public void setFloorId(String floorId)
    {
        this.floorId = floorId;
    }

    public UnitFree(java.awt.Frame parent, boolean modal, String idfloor){
        super(parent, modal);
        chua = idfloor;
        initComponents();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents()
    {

        jScrollPane1 = new javax.swing.JScrollPane();
        tbdulieu = new javax.swing.JTable();
        btnbuy = new javax.swing.JButton();
        btnexit = new javax.swing.JButton();
        btnInsert = new javax.swing.JButton();
        btnEdit = new javax.swing.JButton();
        btnDelete = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Unit Free");

        Object colNames[] =
        { "", "Unit Name", "Unit Price", "" };
        Object[][] data =
        {};
        dtm = new DefaultTableModel(data, colNames);
        tbdulieu = new JTable(dtm);
        tbdulieu.getTableHeader().setReorderingAllowed(false);
        tbdulieu.getColumnModel().getColumn(0).setMaxWidth(80);
        tbdulieu.getColumnModel().getColumn(0).setMinWidth(80);
        tbdulieu.getColumnModel().getColumn(0).setWidth(50);

        tbdulieu.getColumnModel().getColumn(3).setMaxWidth(0);
        tbdulieu.getColumnModel().getColumn(3).setMinWidth(0);

        tbdulieu.addMouseListener(new MouseAdapter()
        {
            @Override
            public void mouseClicked(MouseEvent e)
            {
                e.consume();
                row = tbdulieu.getSelectedRow();
                click1 = tbdulieu.getValueAt(row, 1).toString();
                click2 = tbdulieu.getValueAt(row, 2).toString();
                click3 = tbdulieu.getValueAt(row, 3).toString();

                a1 = click1;
                a2 = click2;
                a3 = click3;

            }

        });

        try
        {
            Registry registry = LocateRegistry.getRegistry(connectRMI.host, connectRMI.port);
            EtowInterface obj = (EtowInterface) registry.lookup(connectRMI.regis);

            List<GroupClass.UnitClass> x = obj.showunitfreeoftown(chua);

            for(GroupClass.UnitClass d : x)
            {
                String unitid = d.getUnitid();
                String unitname = d.getUnitname();
                String unitprice = d.getUnitprice();

                dtm.addRow(new Object[]
                { new Boolean(false), unitname, unitprice, unitid });
            }

        }catch(Exception ex)
        {
            ex.printStackTrace();
        }
        TableColumn tc = tbdulieu.getColumnModel().getColumn(0);
        tc.setCellEditor(tbdulieu.getDefaultEditor(Boolean.class));
        tc.setCellRenderer(tbdulieu.getDefaultRenderer(Boolean.class));
        tc.setHeaderRenderer(new CheckBoxHeader(new MyItemListener()));

        jScrollPane1.setViewportView(tbdulieu);

        btnbuy.setText("Buy Unit");
        btnbuy.addActionListener(new java.awt.event.ActionListener()
        {
            public void actionPerformed(java.awt.event.ActionEvent evt)
            {
                btnbuyActionPerformed(evt);
            }
        });

        btnexit.setText("Exit");
        btnexit.addActionListener(new java.awt.event.ActionListener()
        {
            public void actionPerformed(java.awt.event.ActionEvent evt)
            {
                btnexitActionPerformed(evt);
            }
        });

        btnInsert.setText("Insert");
        btnInsert.addActionListener(new ActionListener()
        {

            @Override
            public void actionPerformed(ActionEvent arg0)
            {
                InsertUnit iU = new InsertUnit(null, true, getFloorId());
                iU.setCheckvisable("ok");
                iU.setVisible(true);
                while(iU.isVisible() != true)
                {
                    if(iU.getCheckvisable().equals("close"))
                    {
                        reloadtable();

                        break;
                    }
                }
            }
        });

        btnEdit.setText("Edit");
        btnEdit.addActionListener(new ActionListener()
        {

            @Override
            public void actionPerformed(ActionEvent arg0)
            {

                EditUnit eU = new EditUnit(null, true, getFloorId());
                eU.setCheckedit("ok");
                eU.setVisible(true);
                while(eU.isVisible() != true)
                {
                    if(eU.getCheckedit().equals("close"))
                    {
                        reloadtable();
                        break;
                    }
                }
            }
        });

        btnDelete.setText("Delete");
        btnDelete.addActionListener(new ActionListener()
        {

            @Override
            public void actionPerformed(ActionEvent arg0)
            {
                String result = "";
                int i = JOptionPane.showConfirmDialog(null, "Neu Ban Da Chac Chan Hay Chon Ok", null,
                        JOptionPane.YES_NO_OPTION);
                if(i == JOptionPane.YES_OPTION)
                {
                    EtowInterface obj = null;
                    Registry registry;
                    try
                    {
                        registry = LocateRegistry.getRegistry(connectRMI.host, connectRMI.port);
                        obj = (EtowInterface) registry.lookup(connectRMI.regis);
                        dem = 0;
                        for(int j = 0 ; j < tbdulieu.getRowCount() ; j++)
                        {
                            if(tbdulieu.getValueAt(j, 0).toString() == "true")
                            {
                                try
                                {
                                    dem += 1;
                                    result = obj.DeleteUnit(tbdulieu.getValueAt(j, 3).toString());
                                    if(result != "Ok")
                                    {
                                        JOptionPane.showMessageDialog(null, "" + tbdulieu.getValueAt(j, 1)
                                                + " has been deleted");
                                    }

                                }catch(RemoteException e)
                                {
                                    e.printStackTrace();
                                }
                            }
                        }

                        reloadtable();
                    }catch(Exception e)
                    {
                        e.printStackTrace();
                    }
                }
            }
        });

        btnexit.setText("Exit");
        btnexit.addActionListener(new ActionListener()
        {
            @Override
            public void actionPerformed(ActionEvent arg0)
            {
                setVisible(false);
                setCountvalueunit(tbdulieu.getRowCount());
                setCheckviable("close");
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(layout
                .createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)
                .addGroup(
                        layout.createSequentialGroup().addContainerGap().addComponent(btnbuy).addGap(18, 18, 18)
                                .addComponent(btnInsert).addGap(18, 18, 18).addComponent(btnEdit).addGap(18, 18, 18)
                                .addComponent(btnDelete).addGap(18, 18, 18).addComponent(btnexit)
                                .addContainerGap(67, Short.MAX_VALUE)));
        layout.setVerticalGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addGroup(
                layout.createSequentialGroup()
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 156,
                                javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addGroup(
                                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                        .addComponent(btnbuy).addComponent(btnInsert).addComponent(btnEdit)
                                        .addComponent(btnDelete).addComponent(btnexit)).addGap(0, 17, Short.MAX_VALUE)));

        btnbuy.getAccessibleContext().setAccessibleName("");

        pack();
    }// </editor-fold>

    private void reloadtable()
    {
        while(tbdulieu.getRowCount() != 0)
        {
            dtm.removeRow(0);
        }

        try
        {
            Registry registry = LocateRegistry.getRegistry(connectRMI.host, connectRMI.port);
            EtowInterface obj = (EtowInterface) registry.lookup(connectRMI.regis);

            List<GroupClass.UnitClass> x = obj.showunitfreeoftown(getFloorId());

            for(GroupClass.UnitClass d : x)
            {
                String unitid = d.getUnitid();
                String unitname = d.getUnitname();
                String unitprice = d.getUnitprice();

                dtm.addRow(new Object[]
                { new Boolean(false), unitname, unitprice, unitid });
            }

        }catch(Exception ex)
        {
            ex.printStackTrace();
        }

    }

    private void btnbuyActionPerformed(java.awt.event.ActionEvent evt)
    {
        for(int j = 0 ; j < tbdulieu.getRowCount() ; j++)
        {
            if(tbdulieu.getValueAt(j, 0).toString() == "true")
            {
                RegistUnit florf = new RegistUnit(null, true, tbdulieu.getValueAt(j, 3).toString());
                florf.setUnitName(a1);
                florf.setUnitName(a2);
                florf.setVisible(true);
            }
        }
    }

    private void btnexitActionPerformed(java.awt.event.ActionEvent evt)
    {
        setVisible(false);
    }

    /**
     * @param args
     *            the command line arguments
     */
    public static void main(String args[])
    {
        try
        {
            for(javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels())
            {
                if("Nimbus".equals(info.getName()))
                {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        }catch(ClassNotFoundException ex)
        {
            java.util.logging.Logger.getLogger(UnitFree.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }catch(InstantiationException ex)
        {
            java.util.logging.Logger.getLogger(UnitFree.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }catch(IllegalAccessException ex)
        {
            java.util.logging.Logger.getLogger(UnitFree.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }catch(javax.swing.UnsupportedLookAndFeelException ex)
        {
            java.util.logging.Logger.getLogger(UnitFree.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        java.awt.EventQueue.invokeLater(new Runnable()
        {

            public void run()
            {
                UnitFree dialog = new UnitFree(new javax.swing.JFrame(), true, chua);
                dialog.addWindowListener(new java.awt.event.WindowAdapter()
                {

                    @Override
                    public void windowClosing(java.awt.event.WindowEvent e)
                    {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify
    private javax.swing.JButton     btnbuy;
    private javax.swing.JButton     btnexit;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable      tbdulieu;
    private javax.swing.JButton     btnEdit;
    private javax.swing.JButton     btnInsert;
    private javax.swing.JButton     btnDelete;

    // End of variables declaration
    class MyItemListener implements ItemListener
    {
        public void itemStateChanged(ItemEvent e)
        {
            Object source = e.getSource();
            if(source instanceof AbstractButton == false) return;
            boolean checked = e.getStateChange() == ItemEvent.SELECTED;
            for(int x = 0 , y = tbdulieu.getRowCount() ; x < y ; x++)
            {
                tbdulieu.setValueAt(new Boolean(checked), x, 0);
            }
        }
    }

    public static String getA1()
    {
        return a1;
    }

    public static String getA2()
    {
        return a2;
    }

    public static String getA3()
    {
        return a3;
    }
}
